<template>
  <div>
    <!-- 更多账号信息 -->
    <moreAccountInfo ref="moreAccountInfo" v-model="modelData" :platform-list="platformList" :rule-parent-key="['moreAccountInfo']"/>
    <template v-if="showMoreModule">
      <!-- 上刊状态 -->
      <journalStatus ref="journalStatus" v-model="modelData" :is-signed="isSigned"/>
      <!-- 上刊价格 -->
      <journal v-if="showJournal" ref="journal" v-model="modelData" :is-signed="isSigned" :rule-parent-key="['journalKey', 'morePriceInfo']"/>
      <!-- 成本信息 -->
      <cost v-if="showCost" ref="cost" v-model="modelData" :rule-parent-key="['costInfoKey']"/>
      <!-- 分成信息 -->
      <morePrice ref="morePrice" v-model="modelData"/>
      <!-- 更多上刊信息 -->
      <moreJournal v-if="showMoreJournal" ref="moreJournal" v-model="modelData" :is-signed="isSigned" :rule-parent-key="['moreJournalKey']"/>
      <!-- 签约信息 -->
      <signInfo ref="signInfo" v-model="modelData" :is-signed="isSigned" :rule-parent-key="['handoverKey']" @updateFollowUsers="updateFollowUsers"/>
      <!-- 当前签约状态 -->
      <statusManage :detail-info="modelData" is-edit/>
      <!-- 更多运营信息 -->
      <otherInfo ref="otherInfo" v-model="modelData"/>
    </template>
  </div>
</template>
<script>
import moreAccountInfo from './moreAccountInfo';
import journal from './journal';
import journalStatus from './journalStatus';
import moreJournal from './moreJournal';
import morePrice from './morePrice';
import otherInfo from './otherInfo';
import cost from './cost';
import signInfo from './signInfo';
import statusManage from '@/views/resource/detail/model/statusManage';

import { getPlatformConfig } from '@/api/signUp';
import { isJournalPlatform } from '@/views/resource/create/resourceData';

export default {
  components: {
    moreAccountInfo,
    journalStatus,
    journal,
    morePrice,
    moreJournal,
    otherInfo,
    cost,
    signInfo,
    statusManage
  },
  model: {
    prop: 'modelData',
    event: 'changeValue'
  },
  props: {
    modelData: {
      type: Object,
      default: () => ({})
    },
    fromSignUp: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    isSigned: {
      type: Boolean,
      default: false
    },
    platformList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    isCommon() {
      const arr = ['小红书', '抖音', '微博', 'B站'];
      return !arr.includes(this.modelData.platformTypeName);
    },
    isJournalPlatform() {
      return isJournalPlatform(this.modelData.platformTypeName);
    },
    refs() {
      let refs = ['moreAccountInfo'];
      if (this.showMoreModule) {
        refs = ['moreAccountInfo', 'signInfo', 'otherInfo', 'journalStatus', 'morePrice'];
        if (this.showMoreJournal) {
          refs.push('moreJournal');
        }
        if (this.showJournal) {
          refs.push('journal');
        }
        if (this.showCost) {
          refs.push('cost');
        }
      }
      return refs;
    },
    showJournal() {
      return this.isJournalPlatform || this.isExitArrayItem(this.modelData.journalKey.dynamicKey) || this.isExitArrayItem(this.modelData.morePriceInfo.dynamicKey);
    },
    showCost() {
      return !this.isCommon || this.isExitArrayItem(this.modelData.costInfoKey.dynamicKey);
    },
    showMoreJournal() {
      return this.isJournalPlatform || this.isExitArrayItem(this.modelData.moreJournalKey.dynamicKey);
    },
    showMoreModule() {
      return this.isEdit || this.fromSignUp;
    }
  },
  methods: {
    // 获取动态字段
    getDynamic(detailData) {
      return new Promise((resolve, reject) => {
        getPlatformConfig(detailData.platformType).then((res) => {
          if (res.data) {
            this.setDynamic(res.data, detailData);
            resolve(true);
          }
        }).catch(() => {
          reject(false);
        });
      });
    },
    isExitArrayItem(arr) {
      return arr && arr.length;
    },
    // 设置动态字段
    setDynamic(data = [], detailData) {
      const res = data.length && data[0].item || [];
      let configArr = [
        { name: '账号信息', dynamicParentKey: 'moreAccountInfo' }
      ];
      if (this.showMoreModule) {
        const extendArr = [
          { name: '价格信息', dynamicParentKey: 'morePriceInfo' },
          { name: '签约信息', dynamicParentKey: 'handoverKey' },
          { name: '上刊价格', dynamicParentKey: 'journalKey' },
          { name: '成本信息', dynamicParentKey: 'costInfoKey' },
          { name: '更多上刊信息', dynamicParentKey: 'moreJournalKey' }
        ];
        configArr = configArr.concat(extendArr);
      }
      configArr.forEach(item => {
        const findItem = res.find(i => i.name === item.name);
        const newDynamicKey = findItem && findItem.item ? findItem.item : [];
        const oldDynamicData = detailData[item.dynamicParentKey].dynamicKey || [];
        // 回填值
        this.handelDynamic(newDynamicKey, oldDynamicData);
        if (detailData) {
          if (newDynamicKey.length !== oldDynamicData.length) { // 自定义字段配置修改标记为表单变动
            this.modelData.dynamicModify = true;
          }
          this.$set(detailData[item.dynamicParentKey], 'dynamicKey', newDynamicKey);
          const requiredModel = this.getRequired(detailData[item.dynamicParentKey].dynamicKey);
          this.$set(detailData[item.dynamicParentKey], 'requiredModel', requiredModel);
        }
      });
      this.isEdit && this.$emit('setOldData', detailData);// 保存一份旧数据用来对比是否修改内容
      this.clearValidate();
    },
    handelDynamic(list, oldData) {
      list.forEach(i => {
        const oldItem = oldData.find(j => j.id === i.id);
        if (oldItem) {
          if (i.inputType === 1 && oldItem.inputType === 1) {
            let curOldItem = {};
            if (oldItem.options) {
              curOldItem = oldItem.options.find(j => j.value === oldItem.value);
            }
            const curNewItem = i.options.find(j => j.value === oldItem.value);
            if (curNewItem && curOldItem.label === curNewItem.label) {
              i.value = oldItem.value;
            } else {
              i.value = '';
            }
          } else if ((i.inputType === 1 && oldItem.inputType === 0) || (i.inputType === 0 && oldItem.inputType === 1)) {
            i.value = '';
          } else {
            i.value = oldItem.value;
          }
        }
      });
    },
    getRequired(dynamicKey) { // 获取必填字段
      const requiredModel = {};
      dynamicKey.forEach(i => {
        if (i.required) {
          const type = i.inputType === 0 ? '输入' : '选择';
          const validateType = (msg, item) => {
            return (rule, value, callback) => {
              if (item && (item.value || item.value === 0)) {
                callback();
              } else {
                callback(new Error(msg));
              }
            };
          };
          requiredModel[`${i.name}_${i.id}`] = [{ required: true, trigger: 'change', validator: validateType(`请${type}${i.name}`, i) }];
        }
      });
      return requiredModel;
    },
    getValidateForm(parentRefName, formRefName = 'formRef') {
      if (!this.$refs[parentRefName]) return null;
      if (Array.isArray(this.$refs[parentRefName][formRefName])) {
        return this.$refs[parentRefName][formRefName][0] || null;
      } else {
        return this.$refs[parentRefName][formRefName];
      }
    },
    clearValidate() {
      this.$nextTick(() => {
        const promise = [];
        this.refs.forEach(i => {
          promise.push(this.getValidateForm(i));
        });
        promise.forEach(i => {
          i && i.clearValidate();
        });
      });
    },
    validateForm() {
      const promise = [];
      this.refs.forEach(refName => {
        promise.push(this.$refs[refName].validateForm());
      });
      return new Promise((resolve, reject) => {
        Promise.all(promise).then(res => {
          const validateResult = res.every(item => !!item);
          if (validateResult) {
            resolve(true);
          } else {
            reject();
          }
        }).catch((e) => {
          reject(e);
        });
      });
    },
    updateFollowUsers(list) {
      this.$emit('updateFollowUsers', list);
    }
  }
};
</script>
<style lang="scss" scoped>
  ::v-deep {
    .dynamicKey-label {
      .el-form-item__label {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
      .el-form-item__error {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 240px;
      }
    }
    .width240 {
      width: 240px;
    }
    .suffix {
      margin-right: 5px;
      color: #333;
    }
    .item-title {
      position: relative;
      font-size: 14px;
      color: #333333;
      font-weight: bold;
      margin: 0 0 16px 18px;
    }
    .item-title::before {
      content: '';
      position: absolute;
      top: calc(50% - 2px);
      left: -8px;
      width: 4px;
      height: 4px;
      background: #406eff;
    }
    .label-collapse {
      .el-form-item {
        .el-form-item__label {
          line-height: 1.1 !important;
        }
      }
    }
    .el-select .el-input .el-select__caret {
      line-height: 32px !important;
    }
    .response-create-row {
      display: flex;
      flex-wrap: wrap;
      @media only screen and (min-width: 1490px) {
        .responsive-col-lg-8 {
          width: 33.33333%;
        }
      }
    }
  }
</style>
<style lang="scss">
  .mobile-create {
    .dynamicKey-label {
      .el-form-item__label {
        justify-content: flex-start !important;
      }
    }
    .cost-item {
      .width300 {
        width: 100% !important;
        .el-input, .el-select, .el-input__inner {
          width: 100% !important;
        }
      }
    }
    .item-top {
      .width120 {
        width: 90px !important;
        .el-input, .el-select, .el-input__inner {
          width: 90px !important;
        }
      }
      .width170 {
        width: 100% !important;
        .el-input, .el-select, .el-input__inner {
          width: 100% !important;
        }
      }
    }
  }
</style>
